﻿using System;
using System.IO;
using System.Reflection;

using HappyTemplate;

namespace OmniUnitTestGenerator
{
	class Program
	{
		static void HandleException(Exception e, string whileFmt, params object[] args)
		{
			if (!String.IsNullOrEmpty(whileFmt))
			{
				Console.Error.WriteLine(whileFmt, args);
			}

			Console.Error.WriteLine("Exception:  {0}\nMessage:  {1}", e.GetType(), e.Message);

			TemplateExecutionException teex = e as TemplateExecutionException;
			if (teex != null)
				Console.Error.WriteLine("Location:  {0}", teex.Location);

			if (e.InnerException != null)
				HandleException(e.InnerException, "Inner Exception:");
		}

		static void Main(string[] args)
		{
			StreamReader sr =
// ReSharper disable AssignNullToNotNullAttribute
				new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("OmniUnitTestGenerator.UnitTests.hts"));
// ReSharper restore AssignNullToNotNullAttribute

			SourceErrorCollection sec;
			TemplateSet templateSet = null;

			try
			{
				templateSet = TemplateParser.ParseTemplateSet(sr, "UnitTests.hts", out sec);
				if (sec.Count > 0)
				{
					sec.PrintAll(Console.Error);
					return;
				}

				templateSet.Context["comparableTypes"] = OmniCompare.GetComparableTypes();


				using(FileStream output = File.Open(@"..\..\..\HappyTemplate.Tests\OmniTests.cs", FileMode.Create))
				using(StreamWriter writer = new StreamWriter(output))
				{
					templateSet.ExecuteTemplate(writer, "main");
				}
			}
			catch (Exception e)
			{
				HandleException(e, "While parsing embedded template set:");
			}

			
		}
	}
}
